<?php

namespace app\shop\controller;

// 框架基础控制类
use think\Controller;

class Base extends Controller
{
    //构造函数
    public function __construct()
    {
        //手动把父类的方法获取过来
        parent::__construct();

        // 全局用户模型
        $this->BusinessModel = model('Business.Business');

    }

    // 注册
    public function register()
    {

        if ($this->request->isPost()) {

            $mobile = $this->request->param('mobile', '', 'trim');

            $password = $this->request->param('password', '', 'trim');

            // 判断当前手机号码是否已注册
            $userinfo = $this->BusinessModel->where('mobile', $mobile)->find();

            if ($userinfo) {
                $this->error('当前手机号码已注册，请重新输入');
            }

            // 密码盐
            $salt = randstr();

            // 密码加密
            $password = md5($password . $salt);

            $data = [
                'mobile' => $mobile,
                'password' => $password,
                'salt' => $salt
            ];

            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if ($result) {
                $this->success('注册成功');
            } else {
                $this->error($this->BusinessModel->getError());
            }
        }
    }

    // 登陆
    public function login()
    {
        if ($this->request->isPost()) {

            $mobile = $this->request->param('mobile', '', 'trim');

            $password = $this->request->param('password', '', 'trim');

            // 查找当前手机号码
            $userinfo = $this->BusinessModel->where('mobile', $mobile)->find();

            if (!$userinfo) {
                $this->error('当前用户不存在');
            }

            $password = md5($password . $userinfo['salt']);

            if ($password != $userinfo['password']) {
                $this->error('密码错误，请重新输入');
            }

            $data = [
                'id' => $userinfo['id'],
                'mobile' => $userinfo['mobile'],
                'nickname' => $userinfo['nickname'],
                'avatar' => $userinfo['avatar_cdn'],
                'gender' => $userinfo['gender'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'district' => $userinfo['district'],
                'point' => $userinfo['point'],
                'region' => $userinfo['region_text'],
                'email' => $userinfo['email'],
                'auth' => $userinfo['auth']
            ];

            $this->success('登陆成功', '',  $data);
        }
    }

}
